package com.atguigu.schedule.controller;

import com.atguigu.schedule.common.Result;
import com.atguigu.schedule.pojo.FaceDetectionRecord;
import com.atguigu.schedule.service.FaceDetectionRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人脸检测记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/face-detection-records")
@RequiredArgsConstructor
public class FaceDetectionRecordController {
    
    private final FaceDetectionRecordService faceDetectionRecordService;
    
    /**
     * 保存人脸检测记录
     */
    @PostMapping("/save")
    public Result<FaceDetectionRecord> saveDetectionRecord(@RequestBody FaceDetectionRecord record) {
        try {
            FaceDetectionRecord saved = faceDetectionRecordService.saveDetectionRecord(record);
            return Result.ok(saved);
        } catch (Exception e) {
            log.error("保存人脸检测记录失败", e);
            return Result.build(null, 500, "保存失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据用户名查找检测记录
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> searchByUsername(
            @RequestParam(required = false) String username,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        try {
            int offset = page * size;
            List<FaceDetectionRecord> records;
            
            if (username != null && !username.trim().isEmpty()) {
                if (startTime != null && endTime != null) {
                    records = faceDetectionRecordService.findByUsernameAndTimeRange(username, startTime, endTime, offset, size);
                } else {
                    records = faceDetectionRecordService.findByUsername(username, offset, size);
                }
            } else {
                if (startTime != null && endTime != null) {
                    records = faceDetectionRecordService.findByTimeRange(startTime, endTime, offset, size);
                } else {
                    // 查询所有记录
                    records = faceDetectionRecordService.findAll(offset, size);
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("records", records);
            result.put("totalElements", records.size());
            result.put("currentPage", page);
            result.put("size", size);
            
            return Result.ok(result);
        } catch (Exception e) {
            log.error("查询人脸检测记录失败", e);
            return Result.build(null, 500, "查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有用户名
     */
    @GetMapping("/usernames")
    public Result<List<String>> getAllUsernames() {
        try {
            List<String> usernames = faceDetectionRecordService.getAllUsernames();
            return Result.ok(usernames);
        } catch (Exception e) {
            log.error("获取用户名列表失败", e);
            return Result.build(null, 500, "获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats/{username}")
    public Result<Map<String, Object>> getUserStats(@PathVariable String username) {
        try {
            long count = faceDetectionRecordService.countByUsername(username);
            FaceDetectionRecord latest = faceDetectionRecordService.getLatestDetectionByUsername(username);
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalDetections", count);
            stats.put("latestDetection", latest);
            
            return Result.ok(stats);
        } catch (Exception e) {
            log.error("获取用户统计信息失败", e);
            return Result.build(null, 500, "获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除过期记录
     */
    @DeleteMapping("/cleanup")
    public Result<String> cleanupOldRecords(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime beforeTime) {
        try {
            faceDetectionRecordService.deleteRecordsBefore(beforeTime);
            return Result.ok("清理完成");
        } catch (Exception e) {
            log.error("清理过期记录失败", e);
            return Result.build(null, 500, "清理失败: " + e.getMessage());
        }
    }
}

